package handler

import (
	"context"
	"fmt"
	"user-server/basic/global"
	"user-server/internal/model"
	__ "user-server/proto"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// 注册
// SayHello implements helloworld.GreeterServer
func (s *Server) Register(_ context.Context, in *__.RegisterRequest) (*__.RegisterResponse, error) {
	add := model.Users1{
		Phone:    in.Phone,
		Password: in.Password,
	}
	global.DB.Debug().Create(&add)
	return &__.RegisterResponse{}, nil
}

// 登录
// SayHello implements helloworld.GreeterServer
func (s *Server) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {
	var user model.Users1
	global.DB.Debug().Where("phone=?", in.Phone).Find(&user)
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	return &__.LoginResponse{}, nil
}

// 添加患者
// SayHello implements helloworld.GreeterServer
func (s *Server) PatientsAdd(_ context.Context, in *__.PatientsAddRequest) (*__.PatientsAddResponse, error) {
	pat := model.Patients{
		Name:         in.Name,
		Age:          int(in.Age),
		Symptom:      in.Symptom,
		Hospitalized: in.Hospitalized,
		Discharge:    in.Discharge,
		Doctor:       in.Doctor,
	}
	global.DB.Debug().Create(&pat)
	return &__.PatientsAddResponse{}, nil
}

// 患者列表
// SayHello implements helloworld.GreeterServer
func (s *Server) PatientsList(_ context.Context, in *__.PatientsListRequest) (*__.PatientsListResponse, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var PatientsList []model.Patients
	global.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Where("LIKE Hospitalized").Find(&PatientsList)
	var list []*__.PatientsList
	for _, v := range PatientsList {
		list = append(list, &__.PatientsList{
			Id:           int64(v.Id),
			Name:         v.Name,
			Age:          int64(v.Age),
			Symptom:      v.Symptom,
			Hospitalized: v.Hospitalized,
			Discharge:    v.Discharge,
			Doctor:       v.Doctor,
		})
	}
	return &__.PatientsListResponse{List: list}, nil
}
